package com.cygsunri.consumption.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cygsunri.consumption.entity.Department;
import com.cygsunri.consumption.mapper.DepartmentMapper;
import com.cygsunri.consumption.service.DepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getDepartmentsByBuildingAndEnergySort(String buildingID, String energySort) {
        return departmentMapper.getDepartmentsByBuildingAndEnergySort(buildingID, energySort);
    }

    @Override
    public List<Department> sortDepartments(List<Department> departments) {
        List<Department> resultList = new ArrayList<>();
        for (Department department : departments) {
            if (StringUtils.isBlank(department.getParent())) {
                resultList.add(department);
                findChildren(department, departments);
            }
        }
        return resultList;
    }

    /**
     * 递归查询下级部门
     */
    private void findChildren(Department parent, List<Department> departments) {
        List<Department> childrenList = new ArrayList<>();

        for (Department d : departments) {
            if (Objects.equals(parent.getId(), d.getParent())) {
                childrenList.add(d);
                findChildren(d, departments);
            }
        }

        if (childrenList.isEmpty()) {
            return;
        }
        parent.setChildren(childrenList);
    }
}
